//
//  WmcTrack.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/3/29.
//

import Alamofire
import RangersAppLog

open class WmcTrack: NSObject {
    struct Param: Encodable {
        let __source__: String
        let __topic__: String
        let __logs__: [[String: String]]
    }

    // Open

    open func addEvent(id: String, params: [String: Any]? = nil) {
        Self.addEvent(id: id, params: params)
    }

    // Public

    public static func addEvent(id: String, params: [String: Any]? = nil) {
        let time = String(Date().timeIntervalSince1970)
        let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown"

        var paramsDic: [String: Any] = [
            "source": YPWmcManager.shared.platform.info.sourceField,
            "version": appVersion,
        ]

        if let params = params {
            paramsDic.merge(params) { (_, new) -> Any in new }
        }

        var dict: [String: Any] = [
            "event_id": id,
            "params": paramsDic,
            "stay_time": "0",
            "time": time,
        ]

        if let accountModel = WmcLoginManager.shared.yupaoAccountModel {
            dict["member_id"] = accountModel.userId
        }

        let json = convertToJsonString(dict: dict)

        if json.isEmpty {
            return
        }

        var sourceStr = "event_prod_syxj"

        let environmentType = YPWmcManager.shared.environmentType
        if environmentType == .develop {
            sourceStr = "event_test_syxj"
        } else if environmentType == .pre_release {
            sourceStr = "event_master_syxj"
        }

        let logs: [[String: String]] = [["json": json]]
        let param = Param(__source__: sourceStr, __topic__: "syxj", __logs__: logs)

        AF.request("http://k8s-log-c797bacd99c4a49a7a71537abeae74e4c.cn-beijing.log.aliyuncs.com/logstores/yupao-datacenter-event/track", method: .post, parameters: param, encoder: JSONParameterEncoder.default, headers: ["x-log-apiversion": "0.6.0", "x-log-bodyrawsize": "1234", "Content-Type": "rwa", "source": "gcdkxj_ios"]).response { response in
            switch response.result {
            case .success:
                print(response)
            case let .failure(error):
                print(error)
            }
        }
    }

    // Internal

    /// 火山埋点自定义事件
    /// - Parameters:
    ///   - eventName: 事件名称
    ///   - params: 参数
    static func addBDAutoTrackEvent(_ eventName: String, params: [String: Any]) {
        BDAutoTrack.eventV3(eventName, params: params)
    }

    // Private

    private static func convertToJsonString(dict: [String: Any]) -> String {
        if (!JSONSerialization.isValidJSONObject(dict)) {
            return""
        }

        var namedPaird: [String] = []

        let sortedValues = dict.sorted { $0.0 < $1.0 }

        for (key, value) in sortedValues {
            if let value = value as? [String: Any] {
                namedPaird.append("\"\(key)\":\(convertToJsonString(dict: value))")

            } else if value is [Any] {
                namedPaird.append("\"\(key)\":\(value)")

            } else {
                namedPaird.append("\"\(key)\":\"\(value)\"")
            }
        }

        let result = namedPaird.joined(separator: ",")

        return"{\(result)}"
    }
}
